package com.ynjtc.desserts.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ynjtc.desserts.entity.Category;
import com.ynjtc.desserts.mapper.CategoryMapper;
import com.ynjtc.desserts.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Author: lihua
 * @Date: 2025/9/15 11:16
 * @Version: v1.0.0
 * @Description:
 **/
@Service
@Slf4j
public class CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private UserMapper userMapper;

    public Category addCategory(Category category){
        QueryWrapper<Category> wrapper = new QueryWrapper<>();
        wrapper.eq("category_name",category.getName()).eq("status",1);
        if( categoryMapper.exists(wrapper)){
            log.error("分类已存在 name ==> {} ", category.getName());
            return null;
        }else {
            categoryMapper.insert(category);
            return category;
        }
    }

    public Page<Category> getAll(){
        Page<Category> categoryPage = new Page<>(3,2);
        return categoryMapper.selectPage(categoryPage,new QueryWrapper<>());
    }

    public void deleteCategory(List<Integer> ids){
        UpdateWrapper<Category> wrapper = new UpdateWrapper<>();
        wrapper.in("id",ids).set("status",0);
        categoryMapper.update(wrapper);
    }

    public Page<Category> getCategory(int num,int page, String name, String describe){
        Page<Category> categoryPage = new Page<>(page,num);
        QueryWrapper<Category> wrapper = new QueryWrapper<>();
        if(StringUtils.isNotEmpty(name))
            wrapper.like("category_name",name);
        if(StringUtils.isNotEmpty(describe))
            wrapper.like("category_describe",describe);
        wrapper.eq("status",1).orderByDesc("create_time");
        return categoryMapper.selectPage(categoryPage,wrapper);
    }

    public Category updateCategoryInfo(Category category){
        Category categoryold = categoryMapper.selectById(category.getId());
        if( categoryold == null){
            return null;
        }else {
            categoryold.setName(category.getName());
            categoryold.setCategoryDescribe(category.getCategoryDescribe());
            categoryMapper.updateById(categoryold);
            return categoryold;
        }
    }



}
